package com.example.websocketserver.configuration.interceptors;

import com.example.websocketserver.pojo.WebSocketConstants;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.http.server.ServletServerHttpRequest;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.WebSocketHandler;
import org.springframework.web.socket.server.HandshakeInterceptor;

import java.util.List;
import java.util.Map;

/**
 * @author liulei
 * @version 1.0
 */
@Component
public class HandleShakeInterceptors implements HandshakeInterceptor {

    private static final Logger log = LoggerFactory.getLogger(HandleShakeInterceptors.class);

    /**
     * 在握手之前执行该方法, 继续握手返回true, 中断握手返回false.
     * 通过attributes参数设置WebSocketSession的属性
     */
    @Override
    public boolean beforeHandshake(ServerHttpRequest request, ServerHttpResponse response,
                                   WebSocketHandler wsHandler, Map<String, Object> attributes) throws Exception {
        String userId = ((ServletServerHttpRequest) request).getServletRequest().getParameter(WebSocketConstants.USER_ID_KEY);
        List<String> host = request.getHeaders().get("host");
        log.info("websocket->handshake-> start connect server {}|{}", host, WebSocketConstants.getUserId(userId));
        //保存客户端标识
        attributes.put(WebSocketConstants.USER_ID_KEY, WebSocketConstants.getUserId(userId));
        return true;
    }

    /**
     * 在握手之后执行该方法. 无论是否握手成功都指明了响应状态码和相应头.
     */
    @Override
    public void afterHandshake(ServerHttpRequest request, ServerHttpResponse response, WebSocketHandler wsHandler, Exception exception) {
        String userId = ((ServletServerHttpRequest) request).getServletRequest().getParameter(WebSocketConstants.USER_ID_KEY);
        List<String> host = request.getHeaders().get("host");
        log.info("websocket->handshake-> complete connect server {}|{}", host, WebSocketConstants.getUserId(userId));
    }
}